//
//  FileManagerHelper.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/8/11.
//

import UIKit

class FileManagerHelper {
    static let shared = FileManagerHelper()
    
    private init() {}

    func fileURL(for url: URL) -> URL {
        let fileName = url.lastPathComponent
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        return documentsDirectory.appendingPathComponent(fileName)
    }
    
    func fileExists(for url: URL) -> Bool {
        let fileURL = fileURL(for: url)
        return FileManager.default.fileExists(atPath: fileURL.path)
    }
    
    func downloadFile(from url: URL, completion: @escaping (Result<URL, Error>) -> Void) {
        let task = URLSession.shared.downloadTask(with: url) { localURL, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let localURL = localURL else {
                completion(.failure(NSError(domain: "FileDownloadError", code: -1, userInfo: nil)))
                return
            }
            
            let destinationURL = self.fileURL(for: url)
            
            do {
                try FileManager.default.moveItem(at: localURL, to: destinationURL)
                completion(.success(destinationURL))
            } catch {
                completion(.failure(error))
            }
        }
        task.resume()
    }
    
    func loadFile(from url: URL, completion: @escaping (Result<URL, Error>) -> Void) {
        if fileExists(for: url) {
            completion(.success(fileURL(for: url)))
        } else {
            downloadFile(from: url, completion: completion)
        }
    }
}
